//
//  AppDelegate.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/7.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import SwiftyJSON
import IQKeyboardManagerSwift
import WisdomHUD
import UserNotifications
import PushKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate, GeTuiSdkDelegate, UNUserNotificationCenterDelegate{
    var window: UIWindow?
    var isPush:Bool = false
    var pushInfo:Dictionary<String, Any> = [:]
    var timer:Timer?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        self.setAppInit()
        self.setUserInfo()
        //用户角色改变
        NotificationCenter.default.addObserver(self, selector: #selector(userTypeChangeAction), name: User_Role_Change_Note, object: nil)
        //登录成功
        NotificationCenter.default.addObserver(self, selector: #selector(userTypeChangeAction), name: Login_Success_Note, object: nil)
        //创建一个定时器
        self.createTimer()
        
        return true
    }
    
    func createTimer(){
        //定时器创建
        weak var weakSelf = self
        self.timer = Timer.init(timeInterval: 30, repeats: true, block: { (timer) in
            weakSelf?.getAppBage()
        })
        RunLoop.main.add(self.timer!, forMode: RunLoop.Mode.common)
        self.timer?.fire()
    }
    
    func getAppBage(){
        if UserModel.share == nil{
            return
        }
        
        LGTHttpUtil.httpUtil.requestData(url: APP_Bage_URL, param: [:], success: { (json) in
            
            print(json)
            let userInfo:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            let appBadgeModel:AppBadgeModel = try! lgtDecode(AppBadgeModel.self, param: (userInfo))
            AppModel.share?.appBadge = appBadgeModel
            NotificationCenter.default.post(name: App_Bage_Note, object: nil, userInfo: [:])
        }) { (json) in
            
        }
    }
    
    @objc func userTypeChangeAction(){
        let mainTabVC:LGTTabBarVC = LGTTabBarVC()
        self.window!.rootViewController = mainTabVC
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: Login_Success_Note, object: nil)
        NotificationCenter.default.removeObserver(self, name: User_Role_Change_Note, object: nil)
        self.timer?.invalidate()
    }
    
    func setAppInit(){
        if #available(iOS 11.0, *){
            UIScrollView.appearance().contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        }else{
        
        }
        IQKeyboardManager.shared.enable = true

        
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: TabBarItemColor, NSAttributedString.Key.font:UIFont.systemFont(ofSize: 12)], for: UIControl.State.normal)
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: TabBarItemSelectColor,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 12)], for: UIControl.State.selected)
            //微信注册
        WXApi.registerApp(WX_APPID)
        //弹窗
        LGTUserUtil.share.clearLLZHomeAlert()
        LGTUserUtil.share.clearRWZHomeAlert()
        //个推
        #if DEBUG
            GeTuiSdk.start(withAppId: "Mb48JBZdc59bb8Ie1XBu28", appKey: "72mB3hIjnL8wBpELEha3H7", appSecret: "7vLHw0MAYx8sBUyjiX6yb8", delegate: self)
        #else
            GeTuiSdk.start(withAppId: "azzzth8Xyy7Em13b7TlzZ2", appKey: "G2Cgjq6h1c6hRyNn7xZMk5", appSecret: "lV20KBuDiA8wSEC5yKLdm2", delegate: self)
        #endif
        self.registerRemoteNotification()
    }
    
    func setUserInfo(){
        //用户信息初始化
        let userInfo:Dictionary<String, Any>? = LGTUserUtil.share.getUserInfo()
//        do{
//            let jsonData = lgtGetJsonData(with: userInfo) ?? Data.init()
//            let model:UserModel =  try JSONDecoder().decode(UserModel.self, from: jsonData)
//        }catch{
//            print(error)
//        }
        if userInfo != nil{
            let userModel:UserModel = try! lgtDecode(UserModel.self, param: userInfo!)
            UserModel.share = userModel
            var tag_id = "tp"
            if userModel.user_type != 1{
                tag_id = "tr"
            }
            let gt_id = String(format:"%@_%ld", tag_id, userModel.user_id ?? 0)
            GeTuiSdk.bindAlias(gt_id, andSequenceNum: "appstore")
        }
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        UIApplication.shared.applicationIconBadgeNumber = 0
        GeTuiSdk.resetBadge()
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return WXApi.handleOpen(url, delegate: self)
    }
    
    func onResp(_ resp: BaseResp!) {
        //微信授权登录 和 绑定微信
        if resp.isKind(of: SendAuthResp.classForCoder()){
            let respResp:SendAuthResp = resp as! SendAuthResp
            let code:String = respResp.code ?? ""
            
            //绑定微信
            if  LGTUserUtil.share.bindWXState == true{
                NotificationCenter.default.post(name: Bind_WX_Note, object: nil, userInfo: ["code":code])
                LGTUserUtil.share.bindWXState = false
                return
            }
            //授权登录
            let param:Dictionary<String, Any> = ["code":code,
                                                 "type": 1]
            //weak var weakSelf = self
            LGTHttpUtil.httpUtil.requestData(url: Login_WX_URL, param: param, showMessage: false, success: { (json) in
                let data:Dictionary<String, Any> = json["data"] as! Dictionary<String,Any>
                var userInfo:Dictionary<String, Any> = json
                userInfo["code"] = respResp.code
                NotificationCenter.default.post(name: WX_Authe_Note, object: nil, userInfo: userInfo)
            }) { (json) in
            }
        }
        //分享后回调类
        else if resp.isKind(of: SendMessageToWXResp.classForCoder()){
            
        }
        //支付后回调类
        else if resp.isKind(of: PayResp.classForCoder()){
            let payResp:PayResp = resp as! PayResp
            if payResp.errCode == WXSuccess.rawValue{
                //print("微信支付成功")
                NotificationCenter.default.post(name: WXPay_ReCharge_Note, object: nil)
            }else{
                WisdomHUD.showError(text: "支付失败")
                //NotificationCenter.default.post(name: WXPay_ReCharge_Note, object: nil)
            }
        }
        //跳转小程序
        else if resp.isKind(of: WXLaunchMiniProgramResp.classForCoder()){
            
        }
    }
    
    //**************个推*******************
    /**
     * [ 参考代码，开发者注意根据实际需求自行修改 ] 注册远程通知
     *
     * 警告：Xcode8及以上版本需要手动开启“TARGETS -> Capabilities -> Push Notifications”
     * 警告：该方法需要开发者自定义，以下代码根据APP支持的iOS系统不同，代码可以对应修改。以下为参考代码
     * 注意根据实际需要修改，注意测试支持的iOS系统都能获取到DeviceToken
     *
     */
    func registerRemoteNotification() {
        let systemVer = (UIDevice.current.systemVersion as NSString).floatValue;
        
        if systemVer >= 10.0 {
            if #available(iOS 10.0, *) {
                let center:UNUserNotificationCenter = UNUserNotificationCenter.current()
                center.delegate = self;
                center.requestAuthorization(options: [.alert,.badge,.sound], completionHandler: { (granted:Bool, error:Error?) -> Void in
                    if (granted) {
                        NSLog("注册通知成功")  // 点击允许
                    } else {
                        NSLog("注册通知失败")  // 点击不允许
                    }
                })
                
                UIApplication.shared.registerForRemoteNotifications()
                
                return;
            }
        }
        
        if systemVer >= 8.0 {
            if #available(iOS 8.0, *) {
                let userSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
                UIApplication.shared.registerUserNotificationSettings(userSettings)
                
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    
    // MARK: - 远程通知(推送)回调
    /// [ 系统回调 ] 远程通知注册成功回调，获取DeviceToken成功，同步给个推服务器
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token:String = LGTOCBaseUtil.getDeviceToken(deviceToken)
        GeTuiSdk.registerDeviceToken(token)
    }
    
    /// [ 系统回调:可选 ] 远程通知注册失败回调，获取DeviceToken失败，打印错误信息
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        NSLog("[ TestDemo ] [DeviceToken Error]: %@ \n", error.localizedDescription);
    }
    
    // MARK: - iOS 10中收到推送消息
    
    /// [ 系统回调 ] iOS 10 通知方法: APNs通知将要显示时触发
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        // [ 测试代码 ] 日志打印APNs信息
        NSLog("[ TestDemo ] [APNs] willPresentNotification: %@", notification.request.content.userInfo);
        
        //点击进来的
        self.isPush = true
        self.pushInfo = notification.request.content.userInfo as? Dictionary<String, Any> ?? [:]
        
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要，判断是否要提示用户Badge、Sound、Alert
        completionHandler([.badge,.sound,.alert]);
    }
    
    /// [ 系统回调 ] iOS 10 通知方法: APNs点击通知时触发
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        // [ 测试代码 ] 日志打印APNs信息
        NSLog("[ TestDemo ] [APNs] didReceiveNotificationResponse: %@", response.notification.request.content.userInfo);
        
        // [ GTSDK ]：将收到的APNs信息传给个推统计
        GeTuiSdk.handleRemoteNotification(response.notification.request.content.userInfo);
        //点击进来的
        self.isPush = true
        self.pushInfo = response.notification.request.content.userInfo  as? Dictionary<String, Any> ?? [:]
        completionHandler();
    }
    
    // MARK: - APP运行中接收到通知(推送)处理 - iOS 10 以下
    
    /// [ 系统回调 ] App收到远程通知
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        // [ 测试代码 ] 日志打印APNs信息
        NSLog("[ TestDemo ] [APNs] didReceiveRemoteNotification: %@", userInfo);
        
        // [ GTSDK ]：将收到的APNs信息传给个推统计
        GeTuiSdk.handleRemoteNotification(userInfo);
        
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
        completionHandler(UIBackgroundFetchResult.newData);
    }
    
    // MARK: - AppLink 接入
    
    /// [ 系统回调 ] APPLink回调
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        let webUrl = userActivity.webpageURL;
        
        // [ GTSDK ]：处理个推APPLink回执统计
        // APPLink url 示例：https://link.gl.ink/getui?n=payload&p=mid， 其中 n=payload 字段存储用户透传信息，可以根据透传内容进行业务操作。
        let payload = GeTuiSdk.handleApplinkFeedback(webUrl);
        if ((payload) != nil) {
            NSLog("[ TestDemo ]  个推APPLink中携带的用户payload信息:\(String(describing: webUrl)), payload:\(String(describing: payload)) \n\n");
            
            // TODO: 用户可根据具体 payload 进行业务处理
        }
        return true;
    }
    
    // MARK: - GeTuiSdkDelegate
    
    /// [ GTSDK回调 ] SDK启动成功返回cid
    func geTuiSdkDidRegisterClient(_ clientId: String!) {
        // [ GTSDK ]：个推SDK已注册，返回clientId
        NSLog("[ TestDemo ] [GTSdk RegisterClient]:%@\n\n", clientId);
    }
    
    /// [ GTSDK回调 ] SDK收到透传消息回调
    func geTuiSdkDidReceivePayloadData(_ payloadData: Data!, andTaskId taskId: String!, andMsgId msgId: String!, andOffLine offLine: Bool, fromGtAppId appId: String!) {
        
        // 数据转换
        var payloadMsg = "";
        if((payloadData) != nil) {
            payloadMsg = String.init(data: payloadData, encoding: String.Encoding.utf8)!;
        }
        
        //消息待处理
        if self.isPush == true{
            LGTPushUtil.share.pushAction(appdelegate: self, pushInfo: self.pushInfo)
            self.isPush = false
        }
        
        
        // [ 测试代码 ] 控制台打印日志
        let msg:String = "Receive Payload: \(payloadMsg), taskId:\(String(describing: taskId)), messageId:\(String(describing: msgId))";
        NSLog("[ TestDemo ] [GTSdk ReceivePayload]:%@\n\n",msg);
    }
    
    /// [ GTSDK回调 ] SDK收到sendMessage消息回调
    func geTuiSdkDidSendMessage(_ messageId: String!, result: Int32) {
        // [ 测试代码 ] 控制台打印日志
        let msg:String = "sendmessage=\(String(describing: messageId)),result=\(result)";
        NSLog("[ TestDemo ] [GeTuiSdk DidSendMessage]:%@\n\n",msg);
    }

    //**************个推*******************
    
    
}

